package com.myideas.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.myideas.dao.UserDao;
import com.myideas.dao.hibernate.GenericDaoHibernate;
import com.myideas.model.Knowledge;
import com.myideas.model.User;
import com.myideas.service.KnowledgeManager;
import com.myideas.service.SecurityManager;
import com.myideas.service.UserExistsException;

public class KnowledgeManagerImpl extends GenericManagerImpl<Knowledge, Long> implements KnowledgeManager { 

    private com.myideas.service.SecurityManager securityManager;
	private GenericDaoHibernate<Knowledge, Long> knowledgeDao;
    private UserDao userDao;

    public KnowledgeManagerImpl(GenericDaoHibernate<Knowledge, Long> knowledgeDao, UserDao userDao) {
    	super(knowledgeDao);
    	this.knowledgeDao = knowledgeDao;
    	this.userDao = userDao;
    }
    
    /**
     * Set the Dao for communication with the data layer.
     */
    @Required
    public void setUserDao(UserDao dao) {
    	this.userDao = dao;
    }
    
    /**
     * Set the Dao for communication with the data layer.
     */
    @Required
    public void setKnowledgeDao(GenericDaoHibernate<Knowledge, Long> dao) {
        this.knowledgeDao = dao;
    }

    /**
     * {@inheritDoc}
     */
    public Knowledge getKnowledge(String knowledgeId) {
        return knowledgeDao.get(new Long(knowledgeId));
    }

    /**
     * {@inheritDoc}
     */
    public List<Knowledge> getKnowledges(Knowledge knowledge) {
        return knowledgeDao.getAll();
    }
    
    /**
     * {@inheritDoc}
     */
    public void removeKnowledge(String knowledgeId) {
        log.debug("removing knowledge: " + knowledgeId);
        knowledgeDao.remove(new Long(knowledgeId));
    }

	public List<User> getAvailableUsers() {
		return knowledgeDao.getHibernateTemplate().find("from User");
	}

	@Transactional(propagation=Propagation.REQUIRED)
	public Knowledge save(Knowledge knowledge, Long user_fk) {
//      try {
//		knowledge.setUser(userDao.get(user_fk));
		knowledge.setUser(securityManager.getUserLoggedIn());
		return knowledgeDao.save(knowledge);
//    } catch (DataIntegrityViolationException e) {
//        e.printStackTrace();
//        log.warn(e.getMessage());
//        throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
//    } catch (EntityExistsException e) { // needed for JPA
//        e.printStackTrace();
//        log.warn(e.getMessage());
//        throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
//    }
	}

	public void setSecurityManager(SecurityManager securityManager) {
		this.securityManager = securityManager;
	}
}
